package com.cropdoctor.service.impl;

import com.cropdoctor.mapper.SysRequestPathPermissionRelationMapper;
import com.cropdoctor.mapper.SysRequestPathMapper;
import com.cropdoctor.model.po.SysRequestPathPo;
import com.cropdoctor.model.po.SysRequestPathPermissionRelationPo;
import com.cropdoctor.service.SysRequestPathPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysRequestPathPermissionServiceImpl implements SysRequestPathPermissionService {
    @Autowired
    private SysRequestPathPermissionRelationMapper sysRequestPathPermissionRelationMapper;
    @Autowired
    private SysRequestPathMapper sysRequestPathMapper;

    @Override
    public List<SysRequestPathPo> getPathsByPermissionId(Integer permissionId) {
        List<SysRequestPathPermissionRelationPo> relations = sysRequestPathPermissionRelationMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysRequestPathPermissionRelationPo>().eq("permission_id", permissionId)
        );
        if(relations.isEmpty()) return java.util.Collections.emptyList();
        List<Integer> pathIds = relations.stream().map(SysRequestPathPermissionRelationPo::getUrlId).collect(Collectors.toList());
        return sysRequestPathMapper.selectBatchIds(pathIds);
    }

    @Override
    public void setPathsForPermission(Integer permissionId, List<Integer> pathIds) {
        // 先删除原有关系
        sysRequestPathPermissionRelationMapper.delete(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysRequestPathPermissionRelationPo>().eq("permission_id", permissionId));
        // 再插入新关系
        for(Integer pathId : pathIds) {
            SysRequestPathPermissionRelationPo relation = new SysRequestPathPermissionRelationPo();
            relation.setPermissionId(permissionId);
            relation.setUrlId(pathId);
            sysRequestPathPermissionRelationMapper.insert(relation);
        }
    }
} 